package com.sks.web.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.stereotype.Controller;

import com.sks.utils.ValidateCodeUtil;
/***
 * 产生验证码
 *
 */
@Controller("/sks/rand")
public class RandAction extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String randCodeText = ValidateCodeUtil.getRandomStr(4);
		HttpSession session = request.getSession();
		session.setAttribute("randCode", randCodeText) ; 
		
		response.setContentType("image/jpeg"); 
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control", "no-cache"); 
		response.setDateHeader("Expires", 0); 


		
		BufferedImage bufferedImage = ValidateCodeUtil.getBuggeredImage(randCodeText);

		ServletOutputStream out = response.getOutputStream(); 
		try {
		    ImageIO.write(bufferedImage, "jpg", out);
		    out.flush();
		} catch (IOException e) {
		    e.printStackTrace();
		} finally{
			out.close(); 
		}
		 
		return null;
	}

}
